﻿using System;
using System.Data.SqlServerCe;
using System.IO;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;

namespace Framework.Repository.Testing
{
    public sealed class SqlServerCePersistence : IPersistence
    {
        private readonly string dbFile;

        public SqlServerCePersistence()
        {
            dbFile = string.Format("{0}{1}", Path.GetTempPath(), Guid.NewGuid());
        }

        public IPersistenceConfigurer CreateConfigurer()
        {
            Console.WriteLine(@"    using db file : {0}", dbFile);

            new SqlCeEngine(string.Format("Data Source={0};Persist Security Info=False;", dbFile)).CreateDatabase();

            var persistenceConfigurer = MsSqlCeConfiguration.Standard.ShowSql().ConnectionString(string.Format("Data Source={0};Persist Security Info=False;", dbFile));
            return persistenceConfigurer;
        }

        public void BuildSchema(ISessionFactory sessionFactory, Configuration configuration)
        {
            new SchemaUpdate(configuration).Execute(true, true);
        }

        public void Dispose()
        {
            if (File.Exists(dbFile))
            {
                File.Delete(dbFile);
            }
        }
    }
}